<?
!defined('IN_HDWIKI') && exit('Access Denied');
class control extends base{

	function control(& $get,& $post){
		$this->base( & $get,& $post);
		$this->load('db');
		$this->view->setlang($this->setting['lang_name'],'back');
	}
	/*db backup*/
	function dobackup(){
		set_time_limit(0);
		$filedir=HDWIKI_ROOT."/data/db_backup/";
		file::createaccessfile($filedir);
		if(!isset($this->post['backupsubmit'])&&!isset($this->get[9])){
			$sqlfilename=date("Ymd",$this->time)."_".util::random(8);
			$tables=$_ENV['db']->showtables();
			file::forcemkdir($filedir);
			$filename=$_ENV['db']->get_sqlfile_list($filedir);
			$this->view->assign('filename',$filename);
			$this->view->assign('filedir',$filedir);
			$this->view->assign('tables',$tables);
			$this->view->assign('sqlfilename',$sqlfilename);
			$this->view->display("admin_dbbackup");
		}else{
			$sqldump = '';
			$type=isset($this->post['type'])?$this->post['type']:$this->get[2];
			$sqlfilename=isset($this->post['sqlfilename'])?$this->post['sqlfilename']:rawurldecode($this->get[3]);
			$sizelimit=isset($this->post['sizelimit'])?$this->post['sizelimit']:intval($this->get[4]);
			$tableid = intval($this->get[5]);
			$startfrom = intval($this->get[6]);
			$volume = intval($this->get[7]) + 1;
			$compression=isset($this->post['compression'])?$this->post['compression']:intval($this->get[8]);
			$backupfilename=$filedir.$sqlfilename;
			$backupsubmit=1;
			$tables=array();
			if(substr(trim(ini_get('memory_limit')),0,-1)<32&&substr(trim(ini_get('memory_limit')),0,-1)>0){
				@ini_set('memory_limit','32M');
			}
			if(!util::is_mem_available($sizelimit*1024*3)){
				$this->message($sizelimit."KB".$this->view->lang['dblimitsizeBig'],'index.php?admin_db-backup');
			}
			switch($type){
				case "full":
					$tables=$_ENV['db']->showtables();
					break;
				case "stand":
					$tables=array(DB_TABLEPRE."category",DB_TABLEPRE."doc",DB_TABLEPRE."edition",DB_TABLEPRE."user");
					break;
				case "min":
					$tables=array(DB_TABLEPRE."doc",DB_TABLEPRE."user");
					break;
				case "custom":
					if(!(bool)$this->post['tables']){
						$tables=$this->cache->getcache('backup_tables','0');
					}else{
						$tables=$this->post['tables'];
						$this->cache->writecache('backup_tables', $tables);
					}
					break;
			}
			if($sizelimit<512){$this->message($this->view->lang['dblimitsizeSmall'],'BACK');}
			if(count($tables)==0){$this->message($this->view->lang['dbChooseOne'],'BACK');}
			if(!file_exists($filedir)) {file::forcemkdir($filedir);}
			if(!file::iswriteable($filedir)){$this->message($this->view->lang['dbFileNotWrite'],'index.php?admin_db-backup');}
			if(in_array(DB_TABLEPRE."usergroup",$tables)){
				$num=array_search(DB_TABLEPRE."usergroup",$tables);
				$tables[$num]=$tables[0];
				$tables[0]=DB_TABLEPRE."usergroup"; 
			}
			if(in_array(DB_TABLEPRE."user",$tables)){
				$num=array_search(DB_TABLEPRE."user",$tables);
				if($tables[0]==DB_TABLEPRE."usergroup"){
					$tables[$num]=$tables[1];
					$tables[1]=DB_TABLEPRE."user"; 
				}else{
					$tables[$num]=$tables[0];
					$tables[0]=DB_TABLEPRE."user"; 
				}
			}
			$complete = TRUE;
			for(; $complete && $tableid < count($tables) && strlen($sqldump) + 500 < $sizelimit * 1000; $tableid++) {
				$result=$_ENV['db']->sqldumptable($tables[$tableid],$complete,$sizelimit, $startfrom, strlen($sqldump));
				$sqldump .= $result['tabledump'];
				$complete=$result['complete'];
				if($complete) {
					$startfrom = 0;
				}else{
					$startfrom = $result['startfrom'];
				}
			}
			$dumpfile = $backupfilename."_%s".'.sql';
			!$complete && $tableid--;
			if(trim($sqldump)) {
				$result=$_ENV['db']->write_to_sql($sqldump,$dumpfile,$volume);
				if(!$result){
					$this->message($this->view->lang['dbBackupWriteSqlFiled'],'BACK');
				}else{
					$url="index.php?admin_db-backup-$type-".rawurlencode($sqlfilename)."-$sizelimit-$tableid-$startfrom-$volume-$compression-$backupsubmit";
					$this->message("<image src='style/default/loading.gif'><br />".$this->view->lang['dbBackupNext1'].$volume.$this->view->lang['dbBackupNext2']."<script type=\"text/JavaScript\">setTimeout(\"window.location.replace('$url');\", 2000);</script>",'');
				}
			}else{
				$volume--;
				if($compression){
					$_ENV['db']->write_to_zip($backupfilename,$dumpfile,$volume);
				}
				$this->cache->removecache('backup_tables');
				$this->header("admin_db-backup");
			}
		}
	}
	
	/*db import*/
	function doimport(){
		set_time_limit(0);
		if(substr(trim(ini_get('memory_limit')),0,-1)<32&&substr(trim(ini_get('memory_limit')),0,-1)>0){
			@ini_set('memory_limit','32M');
		}
		$filename=str_replace('*','.',$this->get[2]);
		$filenum=$this->get[3]?$this->get[3]:1;
		$filedir="./data/db_backup/";
		$filetype=$this->get[4]?$this->get[4]:substr($filename,-3);
		if($filetype!='zip'&&$filetype!='sql'){
			$this->message($this->view->lang['dbBackupFormatError'],'BACK');
		}else{
			if($filenum==1){
				if($filetype=='zip'){
					require_once HDWIKI_ROOT.'/lib/zip.class.php';
					$zip=new zip();
					$zip->Extract($filedir.$filename,$filedir);
					$filename=substr($filename,0,-4)."_1.sql";
				}else{
					$num=strrpos($filename,"_");
					$filename=substr($filename,0,$num)."_1.sql";
				}
			}
			if(file_exists($filedir.$filename)){
				$sqldump=file::readfromfile($filedir.$filename);
				$sqlquery = $_ENV['db']->splitsql($sqldump);
				unset($sqldump);
				foreach($sqlquery as $sql) {
					$sql = $_ENV['db']->syntablestruct(trim($sql), $this->db->version() > '4.1', DB_CHARSET);
					if($sql != '') {
						$this->db->query($sql, 'SILENT');
						if(($sqlerror = $this->db->error()) && $this->db->errno() != 1062) {
							$this->db->halt('MySQL Query Error', $sql);
						}
					}
				}
				if($filetype=='zip'){
					@unlink($filedir.$filename);
				}
				$filenum++;
				$num=strrpos($filename,"_");
				$filename=str_replace('.','*',substr($filename,0,$num)."_".$filenum.".sql");
				$url="index.php?admin_db-import-$filename-$filenum-$filetype";
				$this->message("<image src='style/default/loading.gif'><br />".$this->view->lang['dbBackupNext1'].($filenum-1).$this->view->lang['dbBackupNext2']."<script type=\"text/JavaScript\">setTimeout(\"window.location.replace('$url');\", 2000);</script>",'');
			}else{
				$this->cache->removecache('import_files');
				$this->message($this->view->lang['dbSqlImportSuccess'],'index.php?admin_db-backup');
			}
		}
	}
	
	/*remove db file*/
	function doremove(){
		$filename=$this->get[2];
		$filename=str_replace('*','.',$filename);
		$filedir=HDWIKI_ROOT."/data/db_backup/".$filename;
		if(!file::iswriteable($filedir))$this->message($this->view->lang['dbFileCanNotWrite'],'index.php?admin_db-backup');
		if(file_exists($filedir)){
			unlink($filedir);
			$this->message($this->view->lang['dbSqlRemoveSuccess'],'index.php?admin_db-backup');
		}
	}
	
	/*db list*/
	function dotablelist(){
		$dbversion=mysql_get_server_info();
		$ret = $list = array();
		$chip=0;
		$ret=$_ENV['db']->show_table_status();
		$count=count($ret);
		for ($i=0;$i<$count;$i++ ){
			$res=$_ENV['db']->check_table($ret[$i]['Name']);
			$type = $dbversion>'4.1'?$ret[$i]['Engine']:$ret[$i]['Type'];
			$chartset = $dbversion>'4.1'?$ret[$i]['Collation']:'N/A';
			$list[] = array('table'=>$ret[$i]['Name'],
							'type'=>$type, 
							'rec_num'=>$ret[$i]['Rows'],
							'rec_index' =>sprintf(" %.2f KB",$ret[$i]['Data_length']/1024),
							'rec_chip'=>$ret[$i]['Data_free'] ,
							'status'=>$res['Msg_text'],'chartset'=>$chartset);
			$chip+= $ret[$i]['Data_free'];
			if($list[$i]['table']==DB_TABLEPRE."session"){
				$session_chip=$list[$i]['rec_chip'];
				$list[$i]['rec_chip']="0";
				$list[$i]['status']="OK";
			}
		}
		$number=$chip-$session_chip;
		$this->view->assign('num',$number);
		$this->view->assign('tablelist',$list);
		$this->view->display("admin_dboptimize");
	}
	
	/*db optimize*/
	function dooptimize(){
		$tables=$_ENV['db']->show_tables_like();
		$message='';
		foreach ($tables as $table){
			$tag=$_ENV['db']->optimize_table($table);
			if ($tag==0){
				$message .=str_replace('%s',$table,$this->view->lang['talbeOptimizeFail'])."<br>";
			}else{ 
				$message .=str_replace('%s',$table,$this->view->lang['talbeOptimizeSuccess'])."<br>";
			}
		}
		$this->message($message,'index.php?admin_db-tablelist');
	}
	
	/*db repair*/
	function dorepair(){
		$tables=$_ENV['db']->show_tables_like();
		$message='';
		foreach ($tables as $table){
			$tag=$_ENV['db']->repair_table($table);
			if ($tag==0){
				$message .=str_replace('%s',$table,$this->view->lang['talbeRepairFail'])."<br>";
			}else{ 
				$message .=str_replace('%s',$table,$this->view->lang['talbeRepairSuccess'])."<br>";
			}
		}
		$this->message($message,'index.php?admin_db-tablelist');
	}
	
	/*download file*/
	function dodownloadfile(){
		$filename=$this->get[2];
		$filename=str_replace('*','.',$filename);
		$filedir=HDWIKI_ROOT."/data/db_backup/".$filename;
		file::downloadfile($filedir);
	}
}
?>